#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data time : 2022/8/16   5:30 下午
# project   : connet_logic.py
# IDE       : PyCharm
# email     :17600960626@163.com
import logging
import os
import time

import subprocess

from keyboard_monitor.ding_messge import dev_messge, un_messge, stop_msg
from driver.android import Action
from lib.read_sql import db

swk_path='//*[@resource-id="com.touchtype.swiftkey:id/toolbar_frame"]'
kika_path = '//*[@resource-id="com.huawei.ohos.inputmethod:id/keyboard_keys_container"]'
kika_hand = '//*[@resource-id="com.huawei.ohos.inputmethod:id/keyboard_keys_container"]'
gboard_path = '//*[@resource-id="com.google.android.inputmethod.latin:id/input_area"]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]'
file = '/Users/xm123/PycharmProjects/KeyboardEfficiencyTest-Tools/report/'


def number_reports(paths):
    #记录弹起次数
    files =[]
    num = 0
    for parent, dirnames, filnames in os.walk(paths):
        for paths in filnames:
            path = os.path.join(paths)
            if '.DS_Store' not in path:
                files.append(path)
    for i in files:
        if os.path.splitext(i)[-1] ==".log":
            num+=1
    return num


def devices_log(times, devices):
    #下载log日志
    logcat_filename = file + times + "-" + devices + '.log'
    logcat_file = open(logcat_filename, "w")
    logcmd = 'adb -s %s logcat -v time -b all' % devices
    p = subprocess.Popen(logcmd, stdout=logcat_file, stderr=subprocess.PIPE, shell=True)
    time.sleep(3)
    p.terminate()


def wifi_ip(devices):
    # 通过ip连接设备
    cmd = 'adb -s %s tcpip 5555'%devices
    subprocess.getoutput(cmd)
    sql_ip = "SELECT ip FROM ip_tab WHERE devices='%s' AND `code`!=3 AND `code`!=2"%devices
    a=db.selectDb(sql_ip)
    cmd1 = 'adb connect %s:5555' % a[1][0][0]
    subprocess.getoutput(cmd1)
    dr = Action(a[1][0][0])
    if dr.exists_xpath(swk_path) == True:
        print('运行swk')
    elif dr.exists_xpath(kika_path) == True:
        print('运行kika')
    elif dr.exists_xpath(kika_hand) == True:
        logging.warning('运行手写')
    else:
        times = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
        numbs=number_reports(file)
        dev_messge(devices,numbs)  # 发送钉钉通知
        print('触发点击弹起键盘:%s'%devices)
        time.sleep(0.5)
        dr.click_by_point(0.896, 0.866)
        devices_log(times, devices)

def usb_dev(devices):
    #usb连接
    dr = Action(devices)
    if dr.exists_xpath(swk_path) == True:
        logging.warning('运行swk')
    elif dr.exists_xpath(kika_path) == True:
        logging.warning('运行kika')
    elif dr.exists_xpath(kika_hand) == True:
        logging.warning('kika手写运行中')
    elif dr.exists_xpath(gboard_path)== True:
        logging.warning('Gboard手写运行中')
    else:
        times = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
        logging.warning('触发点击弹起键盘:%s'%devices)
        time.sleep(0.5)
        dr.click_by_point(0.896, 0.866)
        devices_log(times, devices)
        num_res=number_reports(file)
        dev_messge(devices,num_res)  # 发送钉钉通知

def unauths(devices):
    #连接异常的设备，更改状态为3
    sql = "SELECT `code` FROM ip_tab WHERE devices='%s'"%devices
    sql_code=db.selectDb(sql)
    if sql_code[1][0][0] == 3:
        pass
    else:
        sql1 = "UPDATE ip_tab set `code`=3 WHERE devices='%s'"%devices
        db.updateDb(sql1)
        un_messge(devices)
        logging.warning('设备发生unauthorized，已被标记')



def stops(devices):
    #设备运行完成监测
    for i in devices:
        cmd = 'adb -s {} shell su -c ls /storage/emulated/0/Android/data/com.huawei.ohos.inputmethod/cache/hand_output_folder/'.format(i)
        adb =subprocess.getoutput(cmd)
        a=adb.split("\n")
        cmd1 = 'adb -s {} shell su -c ls /storage/emulated/0/Android/data/com.google.android.inputmethod.latin/cache/hand_output_folder/'.format(i)
        adb = subprocess.getoutput(cmd1)
        b = adb.split("\n")
        try:
            sql2 = "SELECT `code` FROM ip_tab WHERE devices='{}'".format(i)
            sql_code = db.selectDb(sql2)
            if sql_code[1][0][0] != 2:
                if 'stop.txt' in a:
                    sql =" UPDATE ip_tab SET `code`=2 WHERE devices='{}'".format(i)
                    db.updateDb(sql)
                    stop_msg(i)
                    logging.warning('监测到stop文件，程序停止设备状态已变更,设备id:%s'%i)
            elif sql_code[1][0][0]!=2:
                if 'stop.txt'in b:
                    sql = " UPDATE ip_tab SET `code`=2 WHERE devices='{}'".format(i)
                    db.updateDb(sql)
                    stop_msg(i)
                    logging.warning('监测到stop文件，程序停止设备状态已变更,设备id:%s' % i)
            else:
                logging.warning('程序继续运行')

        except Exception as e:
            logging.warning(e,'程序异常')

